package com.offcn.order.controller;

import com.offcn.common.entity.Result;
import com.offcn.common.entity.StatusCode;
import com.offcn.common.utils.TokenDecode;
import com.offcn.order.pojo.Cart;
import com.offcn.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * 购物车控制器
 *
 * @author 秋林
 * @date 2022/10/13 15:31:31
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/cart" )
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 购物车用户名公共方法
     */
    private  String  name(){
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        System.out.println("用户信息: " + userInfo);
        String username = userInfo.get("username");
        if (StringUtils.isEmpty(username) || username.equals("") ) {
            username="ujiuye";
        }
       return username;
    }

    /**
     * 购物车列表
     *
     * @return
     */
    @RequestMapping("/findCartList")
    public List<Cart> findCartList() {
        String username = name();
        return cartService.findCartListFromRedis(username);
    }

    /**
     * 添加商品到购物车列表
     *
     * @param itemId 项id
     * @param num
     * @return {@link Result}
     */
    @RequestMapping("/addGoodsToCartList")
    public Result addGoodsToCartList(Long itemId, Integer num) {

        String username = name();
        try {
            //获取购物车列表
            List<Cart> cartList = findCartList();
            cartList = cartService.addGoodsToCartList(cartList, itemId, num);
            cartService.saveCartListToRedis(username, cartList);
            return new Result(true, StatusCode.OK, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
    }
}
